package com.wiloon.java8x.gradle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GradleToMaven {
	private static Logger logger = LoggerFactory.getLogger(GradleToMaven.class);

	public static void main(String[] args) {
		GradleToMaven gtm = new GradleToMaven();
		gtm.generateDependencyStr();
	}

	public void generateDependencyStr() {
		// load build.gradle
		List<Dependency> dependencys = new ArrayList();

		try {
			File buildGradle = new File("D:\\workspace\\myProjects\\servletDemo\\servlet3Demo\\build.gradle");
			FileReader reader = new FileReader(buildGradle);
			BufferedReader br = new BufferedReader(reader);
			String str = null;
			String pattern = ".*compile.*'.*:.*:.*'.*";

			while ((str = br.readLine()) != null) {
				logger.debug("read line=" + str);
				Matcher matcher = Pattern.compile(pattern).matcher(str);
				if (matcher.find()) {
					String dependencyStr = str.substring(str.indexOf("'") + 1,
							str.length() - 1);
					String[] dependencyArray = dependencyStr.split(":");
					Dependency dependency = new Dependency();
					dependency.setGroupId(dependencyArray[0]);
					dependency.setArtifactId(dependencyArray[1]);
					dependency.setVersion(dependencyArray[2]);
					dependencys.add(dependency);
				}
			}
			StringBuffer sb = new StringBuffer();
			sb.append("<dependencies>");
			for (Dependency dependency : dependencys) {
				sb.append("<dependency>");
				sb.append("<groupId>");
				sb.append(dependency.getGroupId());
				sb.append("</groupId>");

				sb.append("<artifactId>");
				sb.append(dependency.getArtifactId());
				sb.append("</artifactId>");

				sb.append("<version>");
				sb.append(dependency.getVersion());
				sb.append("</version>");
				sb.append("</dependency>");
			}
			sb.append("</dependencies>");
			logger.debug("Dependencys=" + sb.toString());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// write POM dependency
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class Dependency {
		private String groupId;
		private String artifactId;
		private String version;

		public String getGroupId() {
			return groupId;
		}

		public void setGroupId(String groupId) {
			this.groupId = groupId;
		}

		public String getArtifactId() {
			return artifactId;
		}

		public void setArtifactId(String artifactId) {
			this.artifactId = artifactId;
		}

		public String getVersion() {
			return version;
		}

		public void setVersion(String version) {
			this.version = version;
		}

	}
}
